<template>
  <div>
    <el-dialog title="添加商品"
               :visible="showAddProduct"
               @close="addProductClose">
      <el-alert show-icon
                title="仅展示该达人可带商品，未添加至联盟推广的商品不会显示在列表中。"
                type="warning">
      </el-alert>
      <div class="mt-20">
        <el-input placeholder="请输入商品名称或者ID"
                  v-model="searchVal">
          <el-button slot="append"
                     icon="el-icon-search"
                     @click="productSearchFunc"></el-button>
        </el-input>
      </div>
      <div>
        <el-table :data="addProductTable"
                  stripe
                  v-loading="isLoading"
                  :row-key="getRowKey"
                  ref="tabters"
                  @selection-change="handleSelectionChange">
          <el-table-column type="selection"
                           reserve-selection
                           :selectable="checkboxInit"
                           width="55"> </el-table-column>
          <el-table-column property="date"
                           label="商品信息">
            <template slot-scope="{ row }">
              <div class="flex f-start-center">
                <img style="width: 32px; height: 32px"
                     :src="row.cover"
                     alt="" />
                <div class="f--1 font-size-12 ml-10">
                  <el-tooltip class="item"
                              effect="dark"
                              :content="row.title"
                              placement="top">
                    <div class="ellipsis-1"
                         style="max-width: 265px">
                      {{ row.title }}
                    </div>
                  </el-tooltip>

                  <div class="color-898B8F">
                    <span>售价：{{ row.price }}</span>
                    <span class="ml-10">全部达人佣金：{{ row.cos_ratio }}%</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="达人买样返款门槛"
                           width="200">
            <template slot-scope="{ row }">
              达人结算订单≥{{ row.sample.buy_volume_limit }}
            </template>
          </el-table-column>
          <el-table-column label="免费申样"
                           width="100">
            <template slot-scope="{ row }">
              <span v-if="row.sample.apply_style == 1"
                    class="font-size-12">
                <span style="display: inline-block"
                      class="auxo-badge-status-dot">
                </span>
                开启
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="mt-15 flex f-between-center">
        <span>已选{{ selectedProductList.length }}/5</span>
        <el-pagination @current-change="handleCurrentChange"
                       background
                       layout="prev, pager, next"
                       :page-size="5"
                       :total="pageObj.total">
        </el-pagination>
      </div>
      <span slot="footer">
        <el-button type="primary"
                   @click="submitProductFunc">添加</el-button>
        <el-button @click="$emit('update:showAddProduct', false)">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getInvitationPersonCommodityList } from '@/api/invitation'
import crossClass from '@/utils/cross-domain.js'
export default {
  props: ['showAddProduct', 'selectProductList'],
  data() {
    return {
      pageObj: {
        total: 10,
        currentPage: 1,
      },
      searchVal: '',
      addProductTable: [],
      isLoading: false,
      selectedProductList: [],
    }
  },
  methods: {
    checkboxInit(row, index) {
      console.log('selectedProductList', this.selectedProductList)
      if (this.selectedProductList.length >= 5) {
        if (
          this.selectedProductList.findIndex(
            (item) => item.product_id == row.product_id
          ) != -1
        ) {
          return 1
        } else {
          return 0
        }
      } else {
        return 1
      }
    },

    getRowKey(row) {
      //   console.log('getRowKey', row)
      return row.product_id
    },
    handleCurrentChange(e) {
      this.pageObj.currentPage = e
      this.getInvitationPersonCommodityListFunc()
    },
    submitProductFunc() {
      this.$emit(
        'getUserAddProductData',
        JSON.parse(JSON.stringify(this.selectedProductList))
      )
      this.$emit('update:showAddProduct', false)
    },
    productSearchFunc() {
      this.getInvitationPersonCommodityListFunc()
    },
    handleSelectionChange(row) {
      this.selectedProductList = row
    },
    addProductClose() {
      this.$emit('update:showAddProduct', false)
    },
    async getInvitationPersonCommodityListFunc() {
      this.isLoading = true

      const crossInstance = new crossClass()

      let checkUrlOpen = await crossInstance.checkUrlOpen([
        'https://buyin.jinritemai.com/dashboard', //达人广场
        'https://fxg.jinritemai.com/ffa', // 抖店后台
      ])
      let { code, data } = checkUrlOpen
      const TipsFunc = (str, url) => {
        this.$confirm(str, '提示', {
          confirmButtonText: '前往打开',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            window.open(url)
          })
          .catch((err) => {})
          .finally(() => {
            setTimeout(() => {
              that.$router.go(0)
            }, 3000)
          })
      }
      if (code == 200) {
        let douDian = data.find((item) => {
          return (
            item.url == 'https://fxg.jinritemai.com/ffa' && item.status == true
          )
        })
        let darenSquare = data.find((item) => {
          return (
            item.url == 'https://buyin.jinritemai.com/dashboard' &&
            item.status == true
          )
        })
        if (!douDian) {
          let str = '使用该功能需要打开并登录抖店'
          let url = 'https://fxg.jinritemai.com/login/common?from=buyin'
          TipsFunc(str, url)
          crossInstance.closeListen()
          return
        }
        if (!darenSquare) {
          let str = '使用该功能需要打开并登录达人广场'
          let url =
            'https://buyin.jinritemai.com/dashboard/servicehall/daren-square?previous_page_name=3&previous_page_type=4'
          TipsFunc(str, url)
          crossInstance.closeListen()
          return
        }
        // this.searchVal != '' ? (params.query = this.searchVal) : null
        crossInstance
          .sendMessageForPageFunc({
            id: darenSquare.id,
            script: `fetch('https://buyin.jinritemai.com/connection/pc/im/promotion/list?page_size=5&page=${this.pageObj.currentPage}&query=${this.searchVal}',{
                            method: 'GET',
                            })
                            .then((res) => {
                            return res.json()
                            })
                            .then((res) => {
                            window.postMessage({
                                    type_urs: 'wkyy-wtbg',
                                    data: res,
                                    type_page: 'pageMeat',
                                    method: 'send_message_for_page'
                                })
                            })
                        `,
          })
          .then((res) => {
            console.log(res, '11111')
            let { code, data } = res
            if (
              code == 200 &&
              data.code == -1 &&
              data.msg == '您已被关闭推广，无法使用平台功能'
            ) {
              this.$message.error(
                '您暂时还不满足邀约达人的条件，请前往官网开通该权限'
              )
              return
            }
            if (code == 200 && data.code == 0) {
              console.log('datadatadata++++', res)
              let {
                code,
                data: { promotion_list, total_count },
              } = data
              if (code == 0) {
                this.addProductTable = promotion_list
                if (this.selectProductList && this.selectProductList.length) {
                  this.selectProductList.forEach((item) => {
                    const getItemIndex = this.addProductTable.findIndex(
                      (itemse) => {
                        return itemse.product_id == item.product_id
                      }
                    )

                    if (
                      getItemIndex != -1 &&
                      this.selectedProductList.findIndex(
                        (itemss) =>
                          itemss.product_id ==
                          this.addProductTable[getItemIndex].product_id
                      ) == -1
                    ) {
                      //选中

                      this.$refs.tabters.toggleRowSelection(
                        this.addProductTable[getItemIndex]
                      )
                    }
                  })
                }

                this.pageObj.total = total_count
                this.isLoading = false
              }
            }
            crossInstance.closeListen()
          })
          .catch((err) => {
            crossInstance.closeListen()
          })
        setTimeout(() => {
          crossInstance.closeListen()
        }, 2000)
      }
      // let params = {
      //     page: this.pageObj.currentPage,
      //     page_size: 5,
      //     verifyFp: 'verify_lyf5ie1a_PDOUr7Op_Pdw5_4lJ2_92eo_xW2e350m34Zc',
      //     fp: 'verify_lyf5ie1a_PDOUr7Op_Pdw5_4lJ2_92eo_xW2e350m34Zc',
      //     msToken:
      //         'osWlBSs2SxjUfA5wETeOloRQ_QYxmu7iJ0JFlkKgq4osFu-LOmlWY-a8x_vtXr0myw_KcVsBc_RFZPDhAg7cnFbwINgy3IzK-CGHoIVrw-MTF2ya-sSeBw==',
      //     a_bogus:
      //         'mvm0BD8kdEINDfLg53OLfY3qfJa3YZKo0SVkMDgbndfO7y39HMO/9exYQRGvZjEjNs/DIemjy4hbT3nDrQAJ0NmUHWsLWnQ2mgDmKAFZR9gas1geejumE0hO-ib3SFas57NAxc40y75azYT0Aoc75kIWPDayYrtswyG7GflNv9smFj=='
      // }
      // this.searchVal != '' ? (params.query = this.searchVal) : null
      // getInvitationPersonCommodityList(params)
      //     .then((res) => {
      //         console.log(res)
      //         let {
      //             code,
      //             data: { promotion_list, total_count }
      //         } = res
      //         if (code == 0) {
      //             this.addProductTable = promotion_list
      //             this.pageObj.total = total_count
      //             this.isLoading = false
      //         }
      //     })
      //     .catch((err) => {
      //         console.log(err, '1111')
      //     })
    },
  },
  mounted() {
    this.getInvitationPersonCommodityListFunc()
  },
}
</script>

<style scoped>
.el-input-group__append {
  background-color: #409eff;
  color: #ffffff;
  border: 0;
}

.auxo-badge-status-dot {
  border-radius: 50%;
  display: inline-block;
  height: 6px;
  position: relative;
  top: -1px;
  vertical-align: middle;
  width: 6px;
  background-color: #3cc781;
}
</style>
